<?php

namespace App\Http\Controllers\Api\V1;
use App\Models\CouponRecord;
use App\Models\Coupon;
use Illuminate\Support\Facades\Cache;
use App\Services\TransferApple\TransferApple;
use App\Services\TransferApple\TransferAppleRequest;
use App\Services\ExchangeBalance\ExchangeBalance;
use App\Services\ExchangeBalance\ExchangeBalanceRequest;
use App\Http\Controllers\Api\V1\Queries\AppleQuery;
use Brick\Math\RoundingMode;
use App\Http\Controllers\Api\V1\Resources\CouponRecordsResource;
use Carbon\Carbon;

class CouponController extends Controller
{
	
	public function couponMerchantRecords()
	{ 
		$merchant = request()->user();
		
		$couponRecords  = $merchant->couponRecords()->orderByDesc('id')->paginate();

		return CouponRecordsResource::collection($couponRecords);
	}

	public function use()
	{ 
		$merchant = request()->user();
		
		$userId = request("user_id");
		$code = request("code","");

		//$coupon =Coupon::query()->where("code",$code)->first();
		


		$record = CouponRecord::query()->where("user_id",$userId)->where("code",$code)->first();

		if(!$record){
			fail("该优惠卷不存在!");
		}

		if($record->status =="used"){

			fail("优惠卷已被使用!");
		}

		if(strtotime($record->expired_at)<time() ){

			fail("优惠卷已过期!");
		}

		if($record->coupon->scope == "shop"){
			
			 $merchants = str_replace("[","",$record->coupon->merchant_ids);
	        $merchants = str_replace("]","",$merchants);
	        $merchants = str_replace('"',"",$merchants);

	        if(!in_array($merchant->id,$merchants)){
	        	fail("该商户无法核销该优惠卷!");

	        }
		}

		$record->update(['used_at'=>Carbon::now(),"status"=>"used",'merchant_id'=>$merchant->id]);

		return new CouponRecordsResource($record);
	}


	public function records()
	{ 
		$user = request()->user();
		
		$couponRecords = $user->couponRecords()->orderByDesc('id')->paginate();

		return CouponRecordsResource::collection($couponRecords);
	}


	
}
